package com.android.fragmentdemo.definervlayoutmanager
import android.content.Context
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

class DefineGridLayoutManager2(context: Context, spanCount: Int) :
    GridLayoutManager(context, spanCount) {

    override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
        try {
            super.onLayoutChildren(recycler, state)
        } catch (ex: Exception) {
            Log.d(TAG, "errorMsg:${ex.localizedMessage}")
        }
    }

    override fun onInterceptFocusSearch(focused: View, direction: Int): View? {
        var fromPosition = getPosition(focused)
        val lastVisiblePosition = findLastVisibleItemPosition()
        val firstVisiblePosition = findFirstVisibleItemPosition()
        when (direction) {
            View.FOCUS_UP, View.FOCUS_LEFT -> {
                fromPosition -= spanCount
            }

            View.FOCUS_DOWN, View.FOCUS_RIGHT -> {
                fromPosition += spanCount
            }
        }

        if (View.FOCUS_DOWN == direction) {
            if (fromPosition in 0..<itemCount && fromPosition > lastVisiblePosition) {
                scrollToPosition(fromPosition)
                return focused
            }
        } else if (View.FOCUS_UP == direction) {
            if (fromPosition in 0..<itemCount && fromPosition < firstVisiblePosition) {
                scrollToPosition(fromPosition)
                return focused
            }
        }

        return super.onInterceptFocusSearch(focused, direction)
    }

    companion object {
        const val TAG = "DefineGridLayoutManager2"
    }
}